<?php


namespace app\admin\service;

/**
 * Class CurlService curl请求服务类
 * @package app\admin\service
 * Author FashionJune
 */
class CurlService
{

    protected $curl;

    public function __construct()
    {
        $this->curl = curl_init();
    }

    public static function init(){
        return new static();
    }

    public function curl_post($url, $header, $body)
    {
        curl_setopt($this->curl, CURLOPT_URL, $url);
        curl_setopt($this->curl, CURLOPT_POST, 1);
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, json_encode($body));
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($this->curl);
        curl_close($this->curl);
        return $output ? json_decode($output, true) : null;
    }

    public function curl_put($url, $header, $body)
    {
        curl_setopt($this->curl, CURLOPT_URL, $url); //定义请求地址
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, "PUT"); //定义请求类型，当然那个提交类型那一句就不需要了
        curl_setopt($this->curl, CURLOPT_HEADER, 0); //定义是否显示状态头 1：显示 ； 0：不显示
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);//定义header
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);//定义是否直接输出返回流
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, json_encode($body)); //定义提交的数据
        $res = curl_exec($this->curl);
        curl_close($this->curl);//关闭
        return $res ? json_decode($res, true) : null;
    }

    public function curl_delete($url, $header)
    {
        curl_setopt($this->curl, CURLOPT_URL, $url); //定义请求地址
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, "DELETE"); //定义请求类型，当然那个提交类型那一句就不需要了
        curl_setopt($this->curl, CURLOPT_HEADER, 0); //定义是否显示状态头 1：显示 ； 0：不显示
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);//定义header
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);//定义是否直接输出返回流
        $res = curl_exec($this->curl);
        curl_close($this->curl);//关闭
        return $res ? json_decode($res, true) : null;
    }


    public function curl_get($url, $header=[])
    {
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($this->curl, CURLOPT_URL, $url);
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($this->curl);
        curl_close($this->curl);
        return $output ? json_decode($output, true) : null;
    }

}